package com.biconn.bigdata.jstrom.util;


import java.io.IOException;
import java.io.StringReader;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.biconn.bigdata.common.util.StringTools;
import com.google.common.collect.Maps;

/**
 * @Auther: 123774135@qq.com
 * @Date: 2018/8/9 16:00
 * @projectname: botu
 * @Description: xml解析
 */
public class XMLResovlve {

  // private static final String XML_PATH = "//data-flows/data-flow/flowsteps";
	private static final String MAPPERS_PATH = "//mappers/mapping";
	





    public static Document loadXml(String str_xml){
        SAXReader reader = new SAXReader(); //1.创建一个xml解析器对象
        Document document = null;
        try {
            document = reader.read(new StringReader(str_xml));

        } catch (Exception e) {
            e.printStackTrace();
        }
        return document;
    }
    
    @SuppressWarnings("unchecked")
    public static Map<String,Map<String,String>> resovlveProcess(Document document){
    	Map<String,Map<String,String>> map = Maps.newHashMap();
    	 if(null == document){
           throw new NullPointerException("document 不能为空");
       }
    	
		List<Element> roots = document.selectNodes(MAPPERS_PATH);
    	 for(Element el : roots) {
    		 String attr = StringTools.mkString(el.attributeValue("name"));
    		 List<Element> childers = el.selectNodes("mapper");
    		 Map<String,String> childer_map = Maps.newHashMap();
    		 for(Element ch : childers) {
    			 childer_map.put(StringTools.mkString(ch.attributeValue("source")), StringTools.mkString(ch.getText()));
    		 }
    		 map.put(attr, childer_map);
    	 }
    	 return map;
    }



    public static void main(String[] args) throws IOException {
      String str_xml =  IOUtils.toString(Thread.currentThread().getContextClassLoader().getResourceAsStream("mapping.xml"));
      Document doc =   XMLResovlve.loadXml(str_xml);
      Map<String,Map<String,String>> map = XMLResovlve.resovlveProcess(doc);
      System.out.println(map.toString());
      
    }
}
